package interfaz;

import clases.ClsContraladorEventos;
import clases.ClsDatabase;
import clases.ClsMetodos;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JDialog;
import javax.swing.JTable;

/**
 *
 * @author MK
 */
public class dlg_NewUsuario extends javax.swing.JDialog {

    private ClsDatabase bd=new ClsDatabase();
    private ClsMetodos metodos=new ClsMetodos();
    private ClsContraladorEventos contraladorEventos=new ClsContraladorEventos();
    private JTable table;
    private dlgUsuariosMantenimiento dialog;
    private String idusuario="-1";
    private boolean editarUpdate=false;
    String nombre_usuario = "";
    int transaccion = 1;
    DefaultComboBoxModel mlb = new DefaultComboBoxModel();
    /**
     * Creates new form dlg_NewUsuario
     * @param parent
     * @param modal
     */
    public dlg_NewUsuario(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    public dlg_NewUsuario(java.awt.Frame parent, boolean modal,JDialog dialog,JTable tblUsuarios) {
        super(parent, modal);
        initComponents();
        this.setLocationRelativeTo(null);//Centramos la ventana
        this.dialog=(dlgUsuariosMantenimiento) dialog;
        this.table=tblUsuarios;
        metodos._iconJDialog(this);
        Limpiar();
    }
//___________________________________________________________________________________ Soy una barra separadora :)
    public void Nuevo(){
        metodos.comboboxLlenar(cboTipoUsuario, mlb, "SELECT idusuario_tipo,descripcion FROM usuario_tipo where estado='A'");
        Limpiar();
    }
    
    public void ver_editar() {
        Nuevo();
        int fila = table.getSelectedRow();
        if (fila != -1) {
            Object[][] array_datos_usuario = bd.select("usuario", "idusuario,nombre, nombre_usuario, password,email,idusuario_tipo,fecha,estado", "idusuario='" + table.getValueAt(fila, 0) + "'");
            //System.out.println(array_datos_usuario);
            if (array_datos_usuario != null) {
                idusuario = array_datos_usuario[0][0].toString();
                txtNombre.setText(array_datos_usuario[0][1].toString());
                nombre_usuario = array_datos_usuario[0][2].toString();
                txtUsuario.setText(array_datos_usuario[0][2].toString());
                txtPassword.setText(array_datos_usuario[0][3].toString());
                txtCorreo.setText(array_datos_usuario[0][4].toString());
                cboTipoUsuario.setSelectedIndex(mlb.getIndexOf(array_datos_usuario[0][5].toString()));
                chkEstado.setSelected(false);
                if (array_datos_usuario[0][7].toString().equals("A")) {
                    chkEstado.setSelected(true);
                }
                transaccion = 2;
                setVisible(true);
            }
        } else {
            javax.swing.JOptionPane.showMessageDialog(this, "Seleccione el Usuario");
            dispose();
        }
    }

    public void transaccion_datos() {
        if (txtNombre.getText().length() == 0 || txtUsuario.getText().length() == 0 || txtPassword.getText().length() == 0) {
            javax.swing.JOptionPane.showMessageDialog(this, "Ingrese los datos");
            return;
        }
        if (cboTipoUsuario.getSelectedIndex() == -1) {
            javax.swing.JOptionPane.showMessageDialog(this, "Seleccione el Tipo de usuario");
            return;
        }
        String estado = "I";
        if (chkEstado.isSelected()) {
            estado = "A";
        }
        if (transaccion == 1) {
            if (bd.verif_repite("select * from usuario where nombre_usuario='" + txtUsuario.getText().toUpperCase() + "'")) {
                javax.swing.JOptionPane.showMessageDialog(this, "Ya existe el nombre de usuario");
                return;
            }
            bd.insert("usuario", "nombre,nombre_usuario,password,email,idusuario_tipo,fecha,estado",
                    "'" + txtNombre.getText().toUpperCase() + "','" + txtUsuario.getText().toUpperCase() + "','" + txtPassword.getText().toUpperCase() + "','" + txtCorreo.getText().toUpperCase() + "','" + mlb.getElementAt(cboTipoUsuario.getSelectedIndex()) + "',sysdate(),'" + estado + "'");
        } else if (transaccion == 2) {
            if (nombre_usuario.equals(txtUsuario.getText().toUpperCase()) == false) {
                if (bd.verif_repite("select * from usuario where nombre_usuario='" + txtUsuario.getText().toUpperCase() + "'")) {
                    javax.swing.JOptionPane.showMessageDialog(this, "Ya esta ocupado el nombre del usuario");
                    return;
                }
            }
            bd.update("usuario", "nombre='" + txtNombre.getText().toUpperCase() + "',nombre_usuario='" + txtUsuario.getText().toUpperCase() + "',password='" + txtPassword.getText().toUpperCase() + "',email='" + txtCorreo.getText().toUpperCase() + "',idusuario_tipo='" + mlb.getElementAt(cboTipoUsuario.getSelectedIndex()) + "',estado='" + estado + "'", "idusuario='" + idusuario + "'");
        }
        dialog.cargar_usuario("");
        dispose();        
    }
//___________________________________________________________________________________ Soy una barra separadora :)
    public void Cancelar(){
        this.dispose();
    }

    private void Limpiar(){
        txtNombre.setText("");
        txtUsuario.setText("");
        txtPassword.setText("");
        txtCorreo.setText("");
        cboTipoUsuario.setSelectedIndex(-1);
//        tgbActivoTI.setSelected(true);
//        tgbInactivoTI.setSelected(false);
        txtNombre.requestFocus();
        chkEstado.setSelected(false);
    }
//___________________________________________________________________________________ Soy una barra separadora :)
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pln2 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        txtNombre = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        txtUsuario = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        txtPassword = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        txtCorreo = new javax.swing.JTextField();
        jPanel3 = new javax.swing.JPanel();
        jLabel6 = new javax.swing.JLabel();
        cboTipoUsuario = new javax.swing.JComboBox();
        chkEstado = new javax.swing.JCheckBox();
        jLabel8 = new javax.swing.JLabel();
        btnCancelar = new javax.swing.JButton();
        btnGuardar1 = new javax.swing.JButton();
        jLabel10 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        pln2.setBackground(new java.awt.Color(225, 235, 247));
        pln2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos generales"));
        jPanel2.setOpaque(false);
        jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
        jPanel2.add(txtNombre, new org.netbeans.lib.awtextra.AbsoluteConstraints(88, 25, 300, -1));

        jLabel3.setText("Nombre:");
        jPanel2.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(16, 25, -1, 25));

        jLabel4.setText("Usuario:");
        jPanel2.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(16, 55, -1, 25));
        jPanel2.add(txtUsuario, new org.netbeans.lib.awtextra.AbsoluteConstraints(88, 55, 300, -1));

        jLabel5.setText("Password:");
        jPanel2.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(16, 85, -1, 25));
        jPanel2.add(txtPassword, new org.netbeans.lib.awtextra.AbsoluteConstraints(88, 85, 180, -1));

        jLabel7.setText("Correo:");
        jPanel2.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(16, 115, -1, 25));
        jPanel2.add(txtCorreo, new org.netbeans.lib.awtextra.AbsoluteConstraints(88, 115, 300, -1));

        pln2.add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 11, 420, 170));

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos extras"));
        jPanel3.setOpaque(false);
        jPanel3.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel6.setText("Tipo usuario:");
        jPanel3.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(16, 25, -1, 25));

        cboTipoUsuario.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        jPanel3.add(cboTipoUsuario, new org.netbeans.lib.awtextra.AbsoluteConstraints(88, 25, 239, -1));

        chkEstado.setText("Usuario activo");
        jPanel3.add(chkEstado, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 60, -1, 25));

        jLabel8.setText("Estado:");
        jPanel3.add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 60, -1, 25));

        pln2.add(jPanel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 190, 420, 90));

        btnCancelar.setText("Cancelar");
        btnCancelar.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });
        pln2.add(btnCancelar, new org.netbeans.lib.awtextra.AbsoluteConstraints(280, 290, 120, 32));

        btnGuardar1.setText("Aceptar");
        btnGuardar1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnGuardar1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnGuardar1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardar1ActionPerformed(evt);
            }
        });
        pln2.add(btnGuardar1, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 290, 110, 32));

        jLabel10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/fondo_dialog.jpg"))); // NOI18N
        pln2.add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 450, 330));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(pln2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pln2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        Cancelar();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void btnGuardar1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardar1ActionPerformed
        transaccion_datos();
    }//GEN-LAST:event_btnGuardar1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(dlg_NewUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(dlg_NewUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(dlg_NewUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(dlg_NewUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                dlg_NewUsuario dialog = new dlg_NewUsuario(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnGuardar1;
    private javax.swing.JComboBox cboTipoUsuario;
    private javax.swing.JCheckBox chkEstado;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel pln2;
    private javax.swing.JTextField txtCorreo;
    private javax.swing.JTextField txtNombre;
    private javax.swing.JTextField txtPassword;
    private javax.swing.JTextField txtUsuario;
    // End of variables declaration//GEN-END:variables
}
